package com.lanou.lucene;


import org.apache.commons.io.FileUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.CharArraySet;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.junit.Test;

import java.io.File;
import java.nio.file.Paths;
import java.util.Arrays;

/**
 * Description: Hello World!
 * author: 何雨轩
 * Create at: 18/7/9 上午9:56
 */
public class LuceneDemo {

    private static final String INDEX_DIR = "/Users/dllo/Desktop/index";
    private static final String DATA_DIR = "/Users/dllo/Desktop/data";

    @Test
    public void createIndex() throws Exception {
        // 打开文件
        Directory dir = FSDirectory.open(Paths.get(INDEX_DIR));

        CharArraySet set = new CharArraySet(Arrays.asList(new java.lang.String[] {"我", "是", "的", "了", "么"}),true);
        // 创建中文分词器
        Analyzer analyzer = new SmartChineseAnalyzer(set);
        // 使用中文分词器
        IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);
        // 创建写索引
        IndexWriter indexWriter = new IndexWriter(dir, indexWriterConfig);

        // 获取目录
        File dataDir = new File(DATA_DIR);
        // 展示目录下的子文件
        for (File data : dataDir.listFiles()) {
            // 如果是文件的话进行操作排除文件夹
            if (data.isFile()) {
                // 创建空文档
                Document document = new Document();
                // 获取文件名
                String title = data.getName();
                // 键值对 通过建取值
                document.add(new TextField("title", title, Field.Store.YES));

                // 读文件
                String content = FileUtils.readFileToString(data, "utf-8");
                document.add(new TextField("content", content, Field.Store.YES));

                indexWriter.addDocument(document);
            }
        }
        indexWriter.close();
    }

    @Test
    public void search() throws Exception {
        String keyword = "女人";

        // 读取索引目录
        Directory dir = FSDirectory.open(Paths.get(INDEX_DIR));
        IndexReader indexReader = DirectoryReader.open(dir);
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);

        CharArraySet set = new CharArraySet(Arrays.asList(new java.lang.String[] {"我", "是", "的", "了", "么"}),true);
        // 创建标准分词器
        //Analyzer analyzer = new StandardAnalyzer();//标准分词器英文的一词一分
        Analyzer analyzer = new SmartChineseAnalyzer(set);//中文分词器

        // 转化成query对象
        // Query query = new QueryParser("title", analyzer).parse(keyword);// 标题或内容
        Query query = new MultiFieldQueryParser(new String[]{"title", "content"}, analyzer).parse(keyword);
        // 搜索5条
        TopDocs topDocs = indexSearcher.search(query, 5);

        System.out.println("共搜索出" + topDocs.totalHits + "条数据");

        for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
            // 通过索引获取查到的文档
            Document document = indexSearcher.doc(scoreDoc.doc);
            String title = document.get("title");
            System.out.println(title);
            System.out.println("评分为:" + scoreDoc.score);
            System.out.println("--------------------------------------------");
        }
    }
}